package org.example.servlet;

import org.example.DAO.CommentDao;
import org.example.entity.User;
import org.example.impl.CommentDaoImpl;
import org.example.Util.DataSourceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

@WebServlet("/delete-comment")
public class DeleteCommentServlet extends HttpServlet {
    private static final Logger logger = LoggerFactory.getLogger(DeleteCommentServlet.class);
    private CommentDao commentDao;

    @Override
    public void init() throws ServletException {
        this.commentDao = new CommentDaoImpl(DataSourceUtil.getDataSource());
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();

        HttpSession session = request.getSession(false);
        String redirectUrl = request.getParameter("redirectUrl");

        try {
            // 1. 验证用户登录状态
            if (session == null || session.getAttribute("user") == null) {
                out.print("{\"success\":false,\"message\":\"未登录\",\"code\":401}");
                return;
            }

            // 2. 获取并验证参数
            int commentId = validateCommentId(request.getParameter("commentId"));
            User user = (User) session.getAttribute("user");

            // 3. 验证评论所有权
            if (!commentDao.isCommentOwner(commentId, user.getId())) {
                out.print("{\"success\":false,\"message\":\"无权删除此评论\",\"code\":403}");
                return;
            }

            // 4. 执行删除操作
            boolean success = commentDao.deleteComment(commentId, user.getId());

            // 5. 返回标准JSON结果
            if (success) {
                out.print("{\"success\":true,\"message\":\"评论删除成功\",\"redirectUrl\":\"" + redirectUrl + "\"}");
            } else {
                out.print("{\"success\":false,\"message\":\"评论删除失败\"}");
            }

        } catch (IllegalArgumentException e) {
            logger.warn("参数验证失败: {}", e.getMessage());
            out.print(String.format("{\"success\":false,\"message\":\"%s\",\"code\":400}", e.getMessage()));
        } catch (SQLException e) {
            logger.error("数据库错误: {}", e.getMessage());
            out.print("{\"success\":false,\"message\":\"数据库错误\",\"code\":500}");
        } catch (Exception e) {
            logger.error("系统错误: {}", e.getMessage());
            out.print("{\"success\":false,\"message\":\"系统错误\",\"code\":500}");
        } finally {
            out.close();
        }
    }

    private int validateCommentId(String commentIdParam) throws IllegalArgumentException {
        if (commentIdParam == null || commentIdParam.trim().isEmpty()) {
            throw new IllegalArgumentException("评论ID不能为空");
        }
        try {
            return Integer.parseInt(commentIdParam);
        } catch (NumberFormatException e) {
            throw new IllegalArgumentException("无效的评论ID格式");
        }
    }
}